Display Prime Numbers Between Intervals Using User-defined Function

04-11-17 Course- CPP

This program takes two positive integers from user and displays all prime numbers between these two intervals. To perform this task, user-defined function is created which will check whether a number is prime or not.

Prime Numbers Between two Intervals by Making User-defined Function


#include<iostream>
using namespace std;
int check_prime(int num);
int main(){
   int n1,n2,i,flag;
   cout << "Enter two numbers(intervals): ";
   cin >> n1 >> n2;
   cout << "Prime numbers between " << n1 << " and " << n2 << " are: " << endl;
   for(i=n1+1;i<n2;++i)
   {
      flag=check_prime(i);
      if(flag==0)
         cout << i << endl;
   }
   return 0;
}
int check_prime(int num) /* User-defined function to check prime number*/
{
   int j,flag=0;
   for(j=2;j<=num/2;++j){
        if(num%j==0){
            flag=1;
            break;
        }
   }
   return flag;
}

Output


Enter two numbers(intervals): 10 30
Prime numbers between 10 and 30 are: 11 13 17 19 23 29

In this program, all numbers between two intervals is passed to function int check_prime(int num) using for loop. This function checks whether a number is prime or not. If the number is prime it returns 1, if not it return 0.